package cn.kai.pet.service.impl;

import cn.kai.basic.service.impl.BaseServiceImpl;
import cn.kai.pet.domain.PetType;
import cn.kai.pet.mapper.PetTypeMapper;
import cn.kai.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kai
 * @since 2022-06-25
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    /**
     * 查询宠物类型树
     * @return
     */
    @Override
    public List<PetType> queryTree() {
        List<PetType> petTypes = petTypeMapper.loadAll();
        //为了后面找自己的父亲，我们这里可以把整体的部门数据，转换一份成Map<id,petType>
        //Map<Long, PetType> allDepts = petTypes.stream().collect(Collectors.toMap(PetType::getId, dept -> dept));
        Map<Long, PetType> allDepts = new HashMap<>();
        for (PetType petType : petTypes) {
            allDepts.put(petType.getId(),petType);
        }
        //新建一个集合用来存放顶级部门
        List<PetType> firstDepts = new ArrayList<>();

        for (PetType temp : petTypes) {
            //如果父级id为null，则为顶级部门
            if (temp.getPid()==null){
                firstDepts.add(temp);
            }else {
                //以父类id为key值查出父类元素，因为map中赋值为引用类型PetType元素的地址值。所以修改共享有效
                PetType parent = allDepts.get(temp.getPid());
                if (parent != null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return firstDepts;
    }
}
